<template>
  <view class="TUI-message-input-container">
	<view class="TUI-message-input-box">
    <view style="position:absolute;bottom:0;left:0">
      <view class="TUI-message-input" :style="{'display': 'flex','align-items':'flex-end','height': height + 30 + 'rpx'}">
      <image
        class="TUI-icon"
        src="../../../../assets/icon/audio.svg"
      ></image>
      <view v-if="!isAudio" class="TUI-message-input-main" :style="{'height': height + 'rpx'}">
        <textarea
          class="TUI-message-input-area"
          cursor-spacing="20"
          v-model="inputText"
		  disabled="disabled"
        >{{$t('chat.user_disabled')}}</textarea>
		<image v-if="develop1===1" class="image1" src="../../../../../../static/images/zhankai.png"></image>
      </view>
      <view class="TUI-message-input-functions" hover-class="none">
			<image
			  class="TUI-icon"
			  src="../../../../assets/icon/emoji.svg"
			></image>
			<view v-if="inputText == ''">
			  <image
				class="TUI-icon"
				src="../../../../assets/icon/more.svg"
			  ></image>
			</view>
			<view v-else class="icon icon-fasong" style="color:#3370CC ;  font-size:66rpx;"></view>
		  </view>
	  </view>
	</view>

  </view>
  </view>
</template>

<script lang="ts">
import {
  defineComponent,
  watchEffect,
  reactive,
  toRefs,
  onMounted,
	onUnmounted,
  computed,
	nextTick,
	defineExpose,
  getCurrentInstance,
	ref
} from "vue";

import store from "../../../../TUICore/store";
import {
	useI18n
} from "vue-i18n";

const TUIChatInputDisable = defineComponent({
  components: {

  },
  props: {
    text: {
      type: String,
      default: () => {
        return "";
      },
    },
    conversationData: {
      type: Object,
      default: () => {
        return "";
      },
    },
  },
  setup(props,ctx:any) {
	  const that = getCurrentInstance();
		const lsjUpload0 = ref(null)
    const TUIServer: any = uni.$TUIKit.TUIChatServer;
	const {
		t
	} = useI18n();
    const data = reactive({
      firstSendMessage: true,
      inputText: "",
      extensionArea: false,
      sendMessageBtn: false,
      displayFlag: "",
	  develop1:0,
      isAudio: false,				//false状态为键入状态，true状态为语音状态
      displayServiceEvaluation: false,
      displayCommonWords: false,
      displayOrderList: false,
      conversation: computed(() => store.state.timStore.conversation),
			showCameraPop: false,  //拍摄照片或从相册中选择弹框
			showVideoPop: false,  //拍摄视频或从相册中选择
			height: 112,  //输入框起始高度,
			bottom: 0, //输入框位置
			mainBottom:0,//父距离底部高度
			option: {
				// 上传服务器地址，此地址需要替换为你的接口地址
				// url: 'http://hl.j56.com/dropbox/document/upload',
				url: 'https://tapi.i-dock.net/mgr/tool/upload/image',
				// 上传附件的key
				name: 'file',
				// 根据你接口需求自定义请求头,默认不要写content-type,让浏览器自适配
				// 根据你接口需求自定义body参数
				formData: {
					// 'orderId': 1000
					'catalog': 'cms'
				}
			},
			// 选择文件后是否立即自动上传，true=选择后立即上传
			instantly: true,
			// 必传宽高且宽高应与slot宽高保持一致
			width: '200rpx',
			height: '60rpx',
			// 限制允许上传的格式，空串=不限制，默认为空
			formats: '',
			// 文件上传大小限制
			size: 30,
			// 文件回显列表
			files: new Map(),
			// 微信小程序Map对象for循环不显示，所以转成普通数组，不要问为什么，我也不知道
			wxFiles: [],
			// 是否打印日志
			debug: true,
			list:[],
			currentFile: null,
    });


	const alt_bottom = (e)=>{
		data.mainBottom = e
		ctx.emit('alt_bottom',e);
	};
    const handleSwitchAudio = () => {
      data.isAudio = !data.isAudio;
	    if(data.isAudio){
		    data.displayFlag="";
		    closedEmoji();
	    }
    };
	const closedevep=()=>{
		console.log('1111111111111111111111111111111111111111'+JSON.stringify(props.conversationData))
		setTimeout(() => {
		    data.develop1=0
		}, 10)

	}
    const handleEmoji = () => {
		data.isAudio =false
		data.displayFlag = data.displayFlag =="emoji"?"":"emoji";
		data.bottom = data.displayFlag =="emoji" ? 450 : 0;
		alt_bottom(data.bottom);
    };
    const handleExtensions = (e: any) => {
		data.isAudio =false
		data.displayFlag = data.displayFlag =="extension"?"":"extension";
		data.bottom = data.displayFlag =="extension"? 450 : 0;
		alt_bottom(data.bottom)
    };
    const getHeight = (e)=> {
        nextTick(() => {
        console.log("e.detail.heightRpx", e.detail.heightRpx)
		  if(e.detail.heightRpx+36 < 396){
			   data.height = e.detail.heightRpx + 32
		  }
          if (e.detail.heightRpx +36 >= 396) {
			return
          }

        })
   };
    // 发送消息
    const handleSendTextMessage = (e: any) => {
      if (data.inputText.trimEnd()) {
        uni.$TUIKit.TUIChatServer.sendTextMessage(
          JSON.parse(JSON.stringify(data.inputText))
        );
      }
      data.inputText = "";
    };
		//清除消息
		const handleClearMessage = () => {
			const laststr: string = data.inputText.substr(data.inputText.length-1, 1)
			//判断该信息最后是不是表情
			if(laststr == ']') {
				//找出“[”最后出现的位置
				const index = data.inputText.lastIndexOf('[')
				//删除表情重新赋值
				data.inputText = data.inputText.substr(0,index)
				return
			}
			//如果信息内容最后一个字符不是表情,直接删除最后一个字符
      data.inputText = data.inputText.substr(0,data.inputText.length -1)
		};
	//换行符
	const messageAddEnter = ()=>{
		data.inputText = data.inputText+'\n'
			  console.log(data.inputText )
	};
	const closedEmoji=()=>{
		 data.develop1=1;
		 data.displayFlag ="";
	};
	const closedPop = () => {
		 data.displayFlag ="";
		 data.bottom = 0
		 alt_bottom(data.bottom)
	}
    // 处理需要合并的数据
    const handleSend = (emo: any) => {
      data.inputText += emo.name;
      // inputEle.value.focus();
    };
	const develop =()=>{
		console.log('jinlaileme ++++++')
		uni.navigateTo({
			url: '/pages/TUIKit/TUIPages/TUIChat/components/message-input/message/develop?text='+data.inputText
		});
	};
    const handleSendImageMessage = (type: any) => {
      uni.chooseImage({
        sourceType: [type],
        count: 9,
        success: (res) => {
			for(var i =0 ; i < res.tempFilePaths.length;i++){
				(function(i) {
				  setTimeout(function() {
						 var img = {
							 tempFilePaths:[],
							 tempFiles:[{
								 path:"",
								 size:0,
								}
							 ]
						 }
				         //var  img = ""
				         //img = "{"+"\""+"tempFilePaths"+"\""+":["+"\""+res.tempFilePaths[i]+"\""+"],"+"\""+"tempFiles"+"\""+":[{"+"\""+"path"+"\""+":"+"\""+res.tempFiles[i].path+"\""+","+"\""+"size"+"\""+":"+res.tempFiles[i].size+"}]}"
				         // var sendImg = JSON.parse(img)
						 img.tempFilePaths[0]= res.tempFilePaths[i]
						 img.tempFiles[0].path= res.tempFiles[i].path
						 img.tempFiles[0].size= res.tempFiles[i].size
				         uni.getImageInfo({
				           src: res.tempFilePaths[i],
				           success(image) {
				             console.error(image);
				             TUIServer.sendImageMessage(img, image);
				           },
				         });
				        }, (i + 1) * 500);
				    })(i)
			}
        },
      });
			if(type == 'album') {
				data.showCameraPop = false
			}else{
				data.showVideoPop = false
			}
			data.displayFlag=""
			data.bottom = 0
    };

    const handleSendVideoMessage = (type: any) => {
      uni.chooseVideo({
        sourceType: [type],
        // 来源相册或者拍摄
        maxDuration: 60,
        // 设置最长时间60s
        camera: "back",
        // 后置摄像头
        success: (res) => {
          if (res) {
            TUIServer.sendVideoMessage(res);
          }
        },
      });
			if(type == 'album') {
				data.showCameraPop = false
			}else{
				data.showVideoPop = false
			}
    };
    // 某文件上传结束回调(成功失败都回调)
    const onuploadEnd = (item)=> {
    	console.log(`${item.name}已上传结束，上传状态=${item.type}`);

    	// 更新当前状态变化的文件
    	data.files.set(item.name,item);

    	// 演示上传完成后取服务端数据
    	if (item['responseText']) {

    		console.log('演示服务器返回的字符串JSON转对象');
    		data.files.get(item.name).responseText = JSON.parse(item.responseText);
    	  const fildata = data.files.get(item.name)
				const path = data.files.get(item.name).responseText.data.filepath
				const type = path.slice(path.indexOf('.') + 1)
				const fileData = {
				  files: [
				    {
				    name: fildata.name, // 文件名
				    size: fildata.size, //本地文件大小
				    type: type, //文件类型
				    path: fildata.path, //本地文件路径
				    lastModified: 0, // 修改时间
				    },
				  ],
				};
				const message = uni.$TUIKit.createFileMessage({
					to: getToAccount(),
					conversationType: props.conversationData.type,
					payload: { file: fileData },
						onProgress: function(event) { console.log('file uploading:', event) }
					})
				TUIServer.sendFileMessage(message);
			}
    	// 强制更新视图
    	that.proxy!.$forceUpdate()
    	// ---可删除--演示判断是否所有文件均已上传成功
    	let isAll = [...data.files.values()].find(item=>item.type!=='success');
    	if (!isAll) {
    		console.log('已全部上传完毕');
    	}
    	else {
    		console.log(isAll.name+'待上传');
    	}
    };
    // 上传进度回调
    const onprogress = (item) => {
    	// 更新当前状态变化的文件
    	data.files.set(item.name,item);
    	data.currentFile = item.file

    	// 强制更新视图
    	that.proxy!.$forceUpdate()

    };
    // 文件选择回调
    const onChange = (files)=> {
			console.log('hahhsahdhsdf')
    	// 更新选择的文件
    	data.files = files;
    	// 强制更新视图
    	that.proxy!.$forceUpdate()
    };
    // 移除某个文件
    const clear = (name) => {
    	// name=指定文件名，不传name默认移除所有文件
    	lsjUpload0.clear(name);
    };
		const getToAccount = () => {
			if (!props.conversationData || !props.conversationData.conversationID) {
				return '';
			}
			switch (props.conversationData.type) {
				case 'C2C':
					return props.conversationData.conversationID.replace('C2C', '');
				case 'GROUP':
					return props.conversationData.conversationID.replace('GROUP', '');
				default:
					return props.conversationData.conversationID;
			}
		};
    const handleCalling = (value: any) => {
      // #ifdef APP-PLUS
      if (typeof uni.$TUICallKit === "undefined") {
        console.error(
          "请集成 TUICallKit 插件，使用真机运行并且自定义基座调试，请参考官网文档：https://cloud.tencent.com/document/product/269/83857"
        );
        uni.showToast({
          title: "请集成 TUICallKit 插件哦 ～ ",
          icon: "none",
          duration: 3000,
        });
      } else {
        if (data.conversation.type === "GROUP") {

			// that.proxy.$goPage('/note/group/detail', {
			// 	groupId: data.conversation?.groupProfile.groupID,
			// 	groupName: data.conversation?.groupProfile.name,
			// 	pid: props.pid,
			// });
			// var titles = t('chat.select_members')
			that.proxy.$http.get('/mgr/user/group/member/list/data', {
			  gid: data.conversation?.groupProfile.groupID,
			}).then(res => {
			  //res.groupMemberList
				that.proxy.$goPage('/note/group/create',{
					title: t('chat.select_members'),
					type: 3,
					calltype:value,
					pid: props.pid,
					gid: data.conversation?.groupProfile.groupID,
					groupMemberList: JSON.stringify(res.groupMemberList).replace(/&/g,'%26')
				})
			})
          // console.log("data.conversation?.groupProfile.groupID------------------------",data.conversation?.groupProfile.groupID);
          // let userIds = [];
          // that.proxy.$http.get('/mgr/user/group/member/list/data', {
          //   gid: data.conversation?.groupProfile.groupID,
          // }).then(res => {
          //   for (let i = 0; i < res.groupMemberList.length; i++) {
          //     userIds.push(res.groupMemberList[i].User.toString())
          //   }
          //   console.log(userIds+"---------------------");
          //   if (userIds.length > 0) {
          //     uni.$TUICallKit.groupCall({
          //           groupID: data.conversation?.groupProfile.groupID,
          //           userIDList: userIds,
          //           callMediaType: value
          //         },(res) => {
          //           console.log(JSON.stringify(res));
          //         }
          //     );
          //   }
          // });
        }else{
          const { userID } = data.conversation.userProfile;
          console.log("false------------------------");
          uni.$TUICallKit.call(
              {
                userID: userID,
                callMediaType: value,
              },
              (res) => {
                console.log(JSON.stringify(res));
              }
          );
        }
      }
      // #endif

      // #ifdef MP-WEIXIN
      if (typeof uni.$TUICallKit !== "undefined" && uni.$TUICallKit.value?.value !== null) {
        const { userID } = data.conversation.userProfile;
        uni.$TUICallKit.value.call({
          userID: userID,
          type: value
        })
      } else {
        console.error(
            "请集成 TUICallKit 插件哦～，请参考官网文档：https://cloud.tencent.com/document/product/269/83858"
        );
        uni.showToast({
          title: "请集成 TUICallKit 插件哦 ～ ",
          icon: "none",
          duration: 3000,
        });
      }
      // #endif

      // #ifdef H5
      uni.showToast({
        title: "暂不支持",
        icon: "none",
      });
      // #endif
    };

    defineExpose({
			closedPop
		})
    return {
      ...toRefs(data),
      handleExtensions,
      handleSendImageMessage,
      handleSendTextMessage,
      handleSendVideoMessage,
      handleEmoji,
      handleSend,
      handleSwitchAudio,
      handleCalling,
	  that,
	  messageAddEnter,
	  closedEmoji,
	  closedPop,
	  getHeight,
	  handleClearMessage,
	  alt_bottom,
	  onuploadEnd,
	  onprogress,
	  onChange,
	  clear,
	  develop,
	  closedevep,
    };
  },
});
export default TUIChatInputDisable;
</script>
<style lang="scss" scoped>
.image1{
	width: 60rpx;
	height: 60rpx;
}
.developtext{
	color: #9c9c9c;
	writing-mode: horizontal-tb;
	font-size: 20rpx;
}
.TUI-message-input-container {
  background-color: #f2f2f2;
  padding-bottom: 6rpx;
	position: relative;
}
.TUI-message-input-box {
	position: absolute;
	bottom: 0;
	left: 0;
	z-index: 1000;
}
.TUI-message-input {
  display: flex;
  padding:16rpx;
  background-color: #f1f1f1;
  width: 100vw;
	border-top: 1px solid #e1e5eb;
	// position: absolute;
	// bottom: 0;
	// left: 0;
	// z-index: 1000;
}

.TUI-commom-function {
  display: flex;
  flex-wrap: nowrap;
  width: 750rpx;
  height: 106rpx;
  background-color: #f1f1f1;
  align-items: center;
}

.TUI-commom-function-item {
  display: flex;
  width: 136rpx;
  justify-content: center;
  align-items: center;
  font-size: 24rpx;
  color: #ffffff;
  height: 48rpx;
  margin-left: 16rpx;
  border-radius: 24rpx;
  background-color: #00c8dc;
}

.TUI-commom-function-item:first-child {
  margin-left: 48rpx;
}

.TUI-message-input-functions {
  display: flex;
}

.TUI-message-input-main {

   background-color: #ccc;
  flex: 1;
  height: 66rpx;
  margin: 0 10rpx;
  padding: 0 5rpx;
	padding-top:16rpx;
  border-radius: 5rpx;
  display: flex;
  align-items: center;
}

.TUI-message-input-area {
  text-align: center;
  background-color: #ccc;
  width: 100%;
  height: 100%;
}

.TUI-icon {
  width: 56rpx;
  height: 56rpx;
  margin: 0 16rpx;
}

.TUI-Extensions {
  display: flex;
  flex-wrap: wrap;
  width: 100vw;
  height: 450rpx;
  margin-right: 14rpx;
	padding-left: 14rpx;
	background-color: #f1f1f1;
	position:absolute;
	bottom: 0;
	left: 0;
	z-index: 1000;
}

.TUI-Extension-slot {
  width: 128rpx;
  height: 170rpx;
  margin-left: 26rpx;
  margin-right: 26rpx;
  margin-top: 24rpx;
}

.TUI-Extension-icon {
  width: 128rpx;
  height: 128rpx;
}

.TUI-sendMessage-btn {
  display: flex;
  align-items: center;
  margin: 0 10rpx;
}

.TUI-Emoji-area {
	position: relative;
  width: 100vw;
  height: 450rpx;
}

.TUI-Extension-slot-name {
	margin-top:10rpx;
  line-height: 34rpx;
  font-size: 24rpx;
  color: #333333;
  letter-spacing: 0;
  text-align: center;

}

.record-modal {
  height: 300rpx;
  width: 60vw;
  background-color: #000;
  opacity: 0.8;
  position: fixed;
  top: 670rpx;
  z-index: 9999;
  left: 20vw;
  border-radius: 24rpx;
  display: flex;
  flex-direction: column;
}

.record-modal .wrapper {
  display: flex;
  height: 200rpx;
  box-sizing: border-box;
  padding: 10vw;
}

.record-modal .wrapper .modal-loading {
  opacity: 1;
  width: 40rpx;
  height: 16rpx;
  border-radius: 4rpx;
  background-color: #006fff;
  animation: loading 2s cubic-bezier(0.17, 0.37, 0.43, 0.67) infinite;
}

.modal-title {
  text-align: center;
  color: #fff;
}
.camera-pop-item {
	text-align: center;
	height: 100rpx;
	line-height:100rpx;
	border-top: 1px solid #e7eae9;
	font-size: 32rpx;
}
.camera-pop-divider {
	height: 20rpx;
	background-color: rgba(0,0,0,0.6);
}
.icon-xiangce {
	font-size: 54rpx;
	color: #5C6168;
}
.icon-fasong{
	flex: 1;
	height: 62rpx;


	display: flex;
	align-items: center;
}
.icon-jianpan1{
    padding-left:7rpx ;
	padding-right:15rpx ;
	height: 62rpx;


	display: flex;
	align-items: center;
}
@keyframes loading {
  0% {
    transform: translate(0, 0);
  }

  50% {
    transform: translate(30vw, 0);
    background-color: #f5634a;
    width: 40px;
  }

  100% {
    transform: translate(0, 0);
  }
}
</style>
